package com.snoob.springCloudGateway.rateLimiter.filter.keyResolver;

import com.snoob.springcloudalibaba.base.BaseLoginUserInfo;
import com.snoob.springcloudalibaba.enums.SysKeyEnum;
import com.snoob.springcloudalibaba.util.jwt.JwtUtil;
import com.snoob.springcloudalibaba.util.StrUtil;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @描述 基于用户进行限流
 * @作者 lixing
 * @日期 2021/7/18 14:26
 */
public class UserKeyResolver implements KeyResolver {
    @Override
    public Mono<String> resolve(ServerWebExchange exchange) {
        String token = exchange.getRequest().getHeaders().getFirst(SysKeyEnum.TOKEN.getKey());
        if (!StrUtil.isEffective(token)) {
            return Mono.just("default");
        }
        try {
            BaseLoginUserInfo baseLoginUserInfo = JwtUtil.verifyJwtForHs256(token);
            return Mono.just(baseLoginUserInfo.getUserAccount());
        } catch (Exception e) {
            return Mono.just("default");
        }
    }
}

